package com.hddf.project.run;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.hddf.project.service.RunTimeService;
import com.hddf.project.upload_cache.CacheService;

public class AutoRunServlet extends HttpServlet {

	private static final long serialVersionUID = -1476537721353939368L;
	private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
	Timer timer = null;
	Timer othertimer = null;

	public AutoRunServlet() {
		super();
		timer = new Timer();
		othertimer = new Timer();
	}

	public void destroy() {
		timer.cancel();
		super.destroy();
	}

	// 增加或减少天数
	public Date addDay(Date date, int num) {
		Calendar startDT = Calendar.getInstance();
		startDT.setTime(date);
		startDT.add(Calendar.DAY_OF_MONTH, num);
		return startDT.getTime();
	}

	public void init() throws ServletException {
		String str_task_time = this.getInitParameter("task_time");
		// 执行任务的时间0-23
		int task_time = Integer.parseInt(str_task_time);
		Calendar calendar = Calendar.getInstance();
		/*** 定制每日2:00执行方法 ***/
		calendar.set(Calendar.HOUR_OF_DAY, task_time);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date date = calendar.getTime(); // 第一次执行定时任务的时间
		// 如果第一次执行定时任务的时间 小于 当前的时间
		// 此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。
		if (date.before(new Date())) {
			date = this.addDay(date, 1);
		}
		// UpdateHistory task = new UpdateHistory();
		// // timer.schedule(new DeleteTask(), 1000,
		// // 900000);//延时1秒执行,然后每间隔15分钟执行一次删除操作

		// othertimer.schedule(task, date, PERIOD_DAY);

		String uploadPath = this.getInitParameter("upload_path");
		CacheService.setRootPath(uploadPath);
		deleteUpload du = new deleteUpload();
		othertimer.schedule(du, date, PERIOD_DAY);
	}
}

class UpdateHistory extends TimerTask {
	@Override
	public void run() {
		try {
			RunTimeService rts = RunTimeService.getInService();
			rts.updateHistory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class deleteUpload extends TimerTask {

	@Override
	public void run() {
		try {
			CacheService cas = CacheService.getInstance();
			cas.removeOverdueCache();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}